import axios from 'axios'
// 导入store
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 获取vuex中的token
    const token = store.state.user.token
    // 将token加入请求头中
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.data.success === false) {
      // 抛出错误: 返回一个错误状态的promise
      return Promise.reject(new Error(response.data.message))
    } else {
      Message.success(response.data.message)
      return response
    }
  },
  async error => {
    if (error.response.data.code === 10002) {
      await store.dispatch('user/userLogout')
      router.push(`/login?return_url=${router.currentRoute.fullPath}`)
    }
    return Promise.reject(error)
  }
)

export default service
